#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#codeby     道长且阻
#email      ydhcui@suliu.net/QQ664284092
#website    http://www.suliu.net

import os
import sys
import json
import random
import re
import queue
from urllib import parse,request

import util
from log import logger
from models import Userai,Aikey,Quotes,User,Joke

class AI(object):
    def __init__(self):
        self.keylist = [d.data for d in Aikey.select()]
        self.Quotes_count_list=range(Quotes.select().count())

    @classmethod
    def student(self,q,a):
        if q and a:
            try:
                Userai.get(Userai.instr==q,Userai.outstr==a)
            except Userai.DoesNotExist:
                Userai.create(instr=q,outstr=a,level=1)
            return "我学会啦！快来问我吧~"

    def chat(self,userid,inmsg):
        k=1
        try:
            msg=self.tuling(userid,inmsg)
            if self.keyp(msg):
               msg=self.simsimi(inmsg)
               if self.keyp(msg):
                  msg=self.hito(msg)
                  k=0
            if k:
                try:
                    Userai.get(Userai.instr==inmsg,Userai.outstr==msg)
                except Userai.DoesNotExist:
                    Userai.create(instr=inmsg,outstr=msg)#学习
        except:
            msg = "你可以发送 '#帮助' 给我查看更多信息。"

        relist = [(d.level,d.outstr) for d in Userai.select().where(Userai.instr==inmsg)]
        relist_level = [outstr for level,outstr in relist if level]      #筛选用户自定义ai，level=1则为用户ai 有优先权
        if relist_level:
            relist = relist_level
        else:
            relist = [outstr for level,outstr in relist]

        if relist:
            return random.choice(relist)
        return msg

    def keyp(self,value):
        if not value:return 1
        for key in self.keylist:
            sg = re.compile(key.strip(),re.UNICODE).search(value)
            if sg:
                return sg.group()

    def hito(self,msg=None):
        try:
            return Quotes.get(Quotes.id==random.choice(self.Quotes_count_list)).data
        except:
            url="http://api.hitokoto.us/rand"
            data=json.loads(util.get(url))
            return data["hitokoto"]

    def tuling(self,userid,msg):
        KEY = '6cef0009ef698bcfaf5fc578625509d0'
        try:
            url = "http://www.tuling123.com/openapi/api?key=%s&info=%s&userid=%s" \
                %(KEY,parse.quote(msg),userid)
            res = util.get(url)
            result = json.loads(res)
            result = result['url'] if result['code']==200000 else result['text']
        except:
            result = '连接超时'
        return result

    def simsimi(self,msg):
        url = "http://www.simsimi.com/requestChat?lc=zh&ft=1.0&req=%s" \
            %parse.quote(msg)
        res = util.get(url)
        result = json.loads(res)
        result = result['res']
        return result

class CmdManage(object):
    cmdlist = {}
    syslist = {}
    ai = AI()
    def __init__(self,user):
        self.user = user
        self.kwargs = {}
        self.loadfun()

    @classmethod
    def regcmd(self,cmd,type=0):
        """注册用户命令
             cmd   命令
             type  命令等级
        """
        def F(f):
            self.cmdlist[cmd]=(f,type)
            return f
        return F

    @classmethod
    def regsys(self,cmd,type=re.UNICODE):
        """注册系统命令
             cmd   命令
             type  匹配模式
        """
        def F(f):
            self.syslist[cmd]=(f,re.compile(cmd,type))
            return f
        return F

    @classmethod
    def unreg(self,cmd,type='cmd'):
        if type=='cmd':
            if cmd in self.cmdlist.keys():
                self.cmdlist.pop(cmd)
        elif type=='sys':
            if cmd in self.syslist.keys():
                self.syslist.pop(cmd)

    @classmethod
    def loadfun(self,filename='function.py',code='UTF8'):
        with open(filename,'r',encoding=code) as f:
            s = f.read()
            f.close()
        try:s=s.decode('GBK').encode('UTF-8')
        except:s=s
        _globals={}
        exec(s,_globals)

    def init(self,msg):
        if not msg:return
        mlist = msg.split('')
        cmd,args = mlist[0], mlist[1:]

        if cmd in self.cmdlist.keys():
           self.kwargs['oldcmd'] = cmd
           func,type = self.cmdlist[cmd]
           pass                            #判断id等级
           result = func(self.user,self.kwargs).init(*args)
           return result

        for cmd in self.syslist.keys():
            func,rec = self.syslist[cmd]
            isrec = rec.search(msg)
            if isrec:
                result = func(self.user,self.kwargs).init(isrec)
                return result

        msg = msg[1:]   #去掉标识符 #
        return self.ai.chat(self.user.uid,msg)

class QQMessageManage(object):
    adminlist = [664284092]     #管理员QQ列表
    Queue = queue.Queue(0)
    friends = {}              #好友列表
    groups = {}               #群组列表
    CmdList = {}              #命令管理器列表
    QQList = {}               #QQ核心列表
    MessageList = {}          #消息管理列表
    GroupList = []            #在名单中的不会回复

    def run(self,msg):
        #logger.debug(str(msg))
        if isinstance(msg,dict):  #sys_g_msg时有可能会是一个列表  好坑
            poll_type = msg['poll_type']
            if 'to_uin' in msg['value'].keys():
                to_uin = msg['value']['to_uin']
                if to_uin not in self.MessageList.keys():
                    self.MessageList[to_uin] = BaseMessage(self.QQList[to_uin])
                if hasattr(self.MessageList[to_uin],poll_type):
                    self.MessageList[to_uin].init(poll_type,msg['value'])

    @classmethod
    def init(self):
        while True:
            data = self.Queue.get()
            for value in data:
                threading.Thread(target=self.run,args=(value,)).start()

if __name__=='__main__':
    '''
    id = User.get(User.uid=='9D3027F35E1AA5628EC2A26E79062ABB')
    cm=CmdManage(id)
    while True:
        str = input('input str >>>')
        print(cm.init(str))'''

    QQMessageManage.init()

